﻿namespace WorkTool2.Helpers;

public static class ControlExtensions
{
    public static void InvokeIfRequired(this Control control, Action action)
    {
        if (control.InvokeRequired)
        {
            control.Invoke(action);
        }
        else
        {
            action();
        }
    }

    public static void InvokeIfRequiredAsync(this Control control, Action action)
    {
        if (control.InvokeRequired)
        {
            control.BeginInvoke(action);
        }
        else
        {
            action();
        }
    }

    public static async Task InvokeIfRequiredAsync(this Control control, Func<Task> action, CancellationToken cancellationToken = default)
    {
        if (control.InvokeRequired)
        {
            var tcs = new TaskCompletionSource<bool>();

            control.BeginInvoke(new Action(async () =>
            {
                try
                {
                    // 检查取消令牌
                    cancellationToken.ThrowIfCancellationRequested();
                    await action();
                    tcs.SetResult(true);
                }
                catch (OperationCanceledException)
                {
                    tcs.SetCanceled();
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }));

            await tcs.Task;
        }
        else
        {
            cancellationToken.ThrowIfCancellationRequested();
            await action();
        }
    }
}